using ExtensionTools.PublicMethods;
using ExtensionToolsLibraries.PublicClasses.ExtensionException;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ExtensionToolsLibraries.Filters;

public class ExceptionFilter : IAsyncExceptionFilter
{

    /// <summary>
    /// 注册全局异常处理器
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task OnExceptionAsync(ExceptionContext context)
    {
        context.ExceptionHandled = true;
        if (context.Exception is ExceptionWithStatus myException)
        {
            context.Result = new JsonResult(OutPutMethod<string>.Failure(message: myException.Message, statusCode: (int)myException.HttpStatusCode, data: ""));
        }
        else
        {
            context.Result = new JsonResult(OutPutMethod<string>.Failure(message: context.Exception.Message, statusCode: 500, data: ""));
        }
        return Task.CompletedTask;
    }
}